#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: ws_data_source.py 
@version:
@time: 2021/08/18 
"""
import websockets
import asyncio
import json
from TapClientCore.T03_api_body_templates.v1_api_body import DATASOURCE_WS_CUSTOMER_TEST
from TapException.TM import LoadSchemaError


# 创建 body
def build_load_schema_body(data):
    # load schema data attr
    ws_data_body = DATASOURCE_WS_CUSTOMER_TEST.copy()
    ws_data_body.update(data)
    ws_body = {'type': 'testConnection'}
    ws_body["data"] = ws_data_body
    return ws_body


# 加载schema
def ws_load_schema(ws_url, res):
    ws_body = build_load_schema_body(res)

    async def l(ws_url, ws_body):
        async with websockets.connect(ws_url) as ws:
            await ws.send(json.dumps(ws_body))
            while True:
                res = json.loads(await ws.recv())
                # 打印loadSchema结果
                # print(res)
                if res is None:
                    continue
                if res['data']['status'] !='SUCCESS':
                    raise LoadSchemaError
                if res['data']['result'] is None:
                    continue
                if res["data"]["result"]["status"] is None:
                    continue
                if res["data"]["result"]["status"] != "ready":
                    raise LoadSchemaError
                for i in res["data"]['result']["response_body"]["validate_details"]:
                    if i["fail_message"] is not None:
                        print(i["fail_message"])
                        raise LoadSchemaError
                await ws.close()

    try:
        asyncio.get_event_loop().run_until_complete(l(ws_url, ws_body))
    except Exception as e:
        assert str(e) == "code = 1000 (OK), no reason"
    return True
